#include "StdAfx.h"
#include "ProjectResourcesForm.h"
#include "ConsoleForm.h"
#include "Mainform.h"
#include "EditorMaterialSerializerListener.h"
#include "MaterialManagerListener.h"

using namespace OgreUnified;

ProjectResourcesForm::ProjectResourcesForm(void)
{
	InitializeComponent();
	Instance = this;
	
	//m_FileSystemWatcher->Path = "E:\\Projects\\Unity\\HorseStar\\Assets";
	//ConsoleForm::Instance->logMessage(m_FileSystemWatcher->Path);
	//PopulateTree(m_FileSystemWatcher->Path, m_TreeView->Nodes );
	ResourceGroupManager::getSingletonPtr()->initialiseAllResourceGroups();
}

ProjectResourcesForm::~ProjectResourcesForm()
{
	if (components)
	{
		delete components;
	}
}

void ProjectResourcesForm::PopulateTree(System::String^ dir, TreeNodeCollection^nodes)
{
	System::IO::DirectoryInfo^ directory = gcnew System::IO::DirectoryInfo(dir);
	
	for each(System::IO::DirectoryInfo^ d in directory->GetDirectories()) 
	{
		TreeNode^ newnode = gcnew TreeNode(d->Name);
		PopulateTree(d->FullName, newnode->Nodes);

			nodes->Add(newnode);
	}

	for each(System::IO::FileInfo^ f in directory->GetFiles()) 
	{
		TreeNode^ newnode = gcnew TreeNode(f->Name);
		nodes->Add(newnode);
	}
}

void ProjectResourcesForm::InitializeComponent(void)
{
	this->m_ToolStrip = (gcnew System::Windows::Forms::ToolStrip());
	this->m_TreeView = (gcnew System::Windows::Forms::TreeView());
	this->m_FileSystemWatcher = (gcnew System::IO::FileSystemWatcher());
	(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->m_FileSystemWatcher))->BeginInit();
	this->SuspendLayout();
	// 
	// m_ToolStrip
	// 
	this->m_ToolStrip->Location = System::Drawing::Point(0, 0);
	this->m_ToolStrip->Name = L"m_ToolStrip";
	this->m_ToolStrip->Size = System::Drawing::Size(284, 25);
	this->m_ToolStrip->TabIndex = 0;
	this->m_ToolStrip->Text = L"m_ToolStrip";
	// 
	// m_TreeView
	// 
	this->m_TreeView->AllowDrop = true;
	this->m_TreeView->Dock = System::Windows::Forms::DockStyle::Fill;
	this->m_TreeView->HotTracking = true;
	this->m_TreeView->Location = System::Drawing::Point(0, 25);
	this->m_TreeView->Name = L"m_TreeView";
	this->m_TreeView->Size = System::Drawing::Size(284, 237);
	this->m_TreeView->TabIndex = 1;
	this->m_TreeView->NodeMouseDoubleClick += gcnew System::Windows::Forms::TreeNodeMouseClickEventHandler(this, &ProjectResourcesForm::m_TreeView_NodeMouseDoubleClick);
	this->m_TreeView->QueryContinueDrag += gcnew System::Windows::Forms::QueryContinueDragEventHandler(this, &ProjectResourcesForm::m_TreeView_QueryContinueDrag);
	this->m_TreeView->GiveFeedback += gcnew System::Windows::Forms::GiveFeedbackEventHandler(this, &ProjectResourcesForm::m_TreeView_GiveFeedback);
	this->m_TreeView->DragLeave += gcnew System::EventHandler(this, &ProjectResourcesForm::m_TreeView_DragLeave);
	this->m_TreeView->AfterLabelEdit += gcnew System::Windows::Forms::NodeLabelEditEventHandler(this, &ProjectResourcesForm::m_TreeView_AfterLabelEdit);
	this->m_TreeView->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &ProjectResourcesForm::m_TreeView_MouseUp);
	this->m_TreeView->DragDrop += gcnew System::Windows::Forms::DragEventHandler(this, &ProjectResourcesForm::m_TreeView_DragDrop);
	this->m_TreeView->AfterSelect += gcnew System::Windows::Forms::TreeViewEventHandler(this, &ProjectResourcesForm::m_TreeView_AfterSelect);
	this->m_TreeView->MouseEnter += gcnew System::EventHandler(this, &ProjectResourcesForm::m_TreeView_MouseEnter);
	this->m_TreeView->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &ProjectResourcesForm::m_TreeView_MouseMove);
	this->m_TreeView->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &ProjectResourcesForm::m_TreeView_MouseDown);
	this->m_TreeView->DragEnter += gcnew System::Windows::Forms::DragEventHandler(this, &ProjectResourcesForm::m_TreeView_DragEnter);
	this->m_TreeView->NodeMouseClick += gcnew System::Windows::Forms::TreeNodeMouseClickEventHandler(this, &ProjectResourcesForm::m_TreeView_NodeMouseClick);
	this->m_TreeView->ItemDrag += gcnew System::Windows::Forms::ItemDragEventHandler(this, &ProjectResourcesForm::m_TreeView_ItemDrag);
	this->m_TreeView->DragOver += gcnew System::Windows::Forms::DragEventHandler(this, &ProjectResourcesForm::m_TreeView_DragOver);
	this->m_TreeView->MouseLeave += gcnew System::EventHandler(this, &ProjectResourcesForm::m_TreeView_MouseLeave);
	// 
	// m_FileSystemWatcher
	// 
	this->m_FileSystemWatcher->EnableRaisingEvents = true;
	this->m_FileSystemWatcher->IncludeSubdirectories = true;
	this->m_FileSystemWatcher->SynchronizingObject = this;
	this->m_FileSystemWatcher->Renamed += gcnew System::IO::RenamedEventHandler(this, &ProjectResourcesForm::m_FileSystemWatcher_Renamed);
	this->m_FileSystemWatcher->Deleted += gcnew System::IO::FileSystemEventHandler(this, &ProjectResourcesForm::m_FileSystemWatcher_Deleted);
	this->m_FileSystemWatcher->Created += gcnew System::IO::FileSystemEventHandler(this, &ProjectResourcesForm::m_FileSystemWatcher_Created);
	this->m_FileSystemWatcher->Changed += gcnew System::IO::FileSystemEventHandler(this, &ProjectResourcesForm::m_FileSystemWatcher_Changed);
	// 
	// ProjectResourcesForm
	// 
	this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
	this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
	this->ClientSize = System::Drawing::Size(284, 262);
	this->Controls->Add(this->m_TreeView);
	this->Controls->Add(this->m_ToolStrip);
	this->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
		static_cast<System::Byte>(0)));
	this->HideOnClose = true;
	this->Name = L"ProjectResourcesForm";
	this->Text = L"Project Resources";
	(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->m_FileSystemWatcher))->EndInit();
	this->ResumeLayout(false);
	this->PerformLayout();

}

System::Void ProjectResourcesForm::m_TreeView_DragDrop(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e)
{
	if(e->Data->GetDataPresent(DataFormats::FileDrop))
	{
		cli::array<System::String^>^ strs =(cli::array<System::String^>^) e->Data->GetData(DataFormats::FileDrop);
		ConsoleForm::Instance->logMessage(strs[0]);

		System::String^ ext = strs[0];
		
		if(ext->EndsWith(".material"))
		{
		
			
			char*ch = ConvertNetStringToChar(strs[0]);
			
std::ifstream ifs(ch, std::ios::binary|std::ios::in);
if (ifs.is_open())
{
	try
	{
		Ogre::ResourceGroupManager::getSingletonPtr()->addResourceLocation(".\\", "FileSystem");
	
	
	Ogre::DataStreamPtr data_stream(new Ogre::FileStreamDataStream(ch, &ifs, false));
	int readed = 0;
	void* bytes;
	Ogre::String str=	data_stream->getAsString();
	//read(bytes, readed);
//	Ogre::DataStreamPtr newdata_stream = Ogre::ResourceGroupManager::getSingletonPtr()->createResource("test.material");	
	//newdata_stream->write(bytes,readed);

	MaterialManager::getSingletonPtr()->addListener(new MaterialManagerListener());
	MaterialPtr ptr = MaterialManager::getSingletonPtr()->create(str,ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	ptr->compile();

	}
	catch(Ogre::Exception e)
	{
		ConsoleForm::Instance->logMessage(e.getFullDescription());
		//System::Runtime::InteropServices::SEHException::
	}

/*	MaterialManager::getSingletonPtr()->addListener(new MaterialManagerListener());
MaterialManager::getSingletonPtr()->parseScript( data_stream,ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//MaterialPtr mat  = MaterialManager::getSingletonPtr()->create("newmat", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//MaterialSerializer matse;
//matse.parseScript(data_stream,ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

Ogre::StringVectorPtr vp = ResourceGroupManager::getSingleton().listResourceNames( ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::StringVector::iterator it = vp->begin();
for(;it!=vp->end();++it)
{
	ConsoleForm::Instance->logMessage( (*it).c_str() );
}*/


//MaterialPtr mat = MaterialManager::getSingletonPtr()->create("rtes", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//MaterialSerializer mats;
//mats.addListener(new EditorMaterialSerializerListener());
//mats.exportMaterial(mat,"test.material");

	
}

			
			//MaterialManager::getSingletonPtr()->parseScript( ((DataStreamPtr&)*fsds),ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
			
			//sin.close();
			//OgreUnified::DeleteHGlobalAnsi(ch);-			//sin.close

			//Ogre::ScriptCompilerManager::getSingletonPtr()->
			//Material* mat = new Material(MaterialManager::getSingletonPtr(), 
			/*MaterialManager::getSingletonPtr()->parse
			Ogre::MemoryDataStreamPtr str = new Ogre::FileStreamDataStream(
			Ogre::ScriptCompiler* scriptcompiler = new ScriptCompiler();
					
			Ogre::String text("material test{   technique   {   pass {   texture_unit   {   texture GreenSkin.jpg } } }}");
			Ogre::String nname("test");

			scriptcompiler->compile(text,nname,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
			//Ogre::MaterialPtr compilematerial = Ogre::MaterialManager::getSingleton().getByName(nname);
			
			
			//MaterialManager::getSingletonPtr()->create("",
			//ResourceGroupManager::getSingletonPtr()->addResou*/

//Ogre::ScriptCompiler* scriptcompiler = new ScriptCompiler();
//scriptcompiler->compile(text,nname,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);


		}
	}
}

System::Void ProjectResourcesForm::m_TreeView_DragEnter(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e)
{


}

System::Void ProjectResourcesForm::m_TreeView_DragLeave(System::Object^  sender, System::EventArgs^  e)
{
	
}

System::Void ProjectResourcesForm::m_TreeView_DragOver(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e)
{
	// Determine whether string data exists in the drop data. If not, then
   // the drop effect reflects that the drop cannot occur.
   if (  !e->Data->GetDataPresent( DataFormats::FileDrop ) )
   {
      e->Effect = DragDropEffects::None;
      //DropLocationLabel->Text = "None - no string data.";
      return;
   }

   // Set the effect based upon the KeyState.
   if ( (e->KeyState & (8 + 32)) == (8 + 32) && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
   {
      // KeyState 8 + 32 = CTL + ALT
      // Link drag-and-drop effect.
      e->Effect = DragDropEffects::Link;
   }
   else
   if ( (e->KeyState & 32) == 32 && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
   {
      // ALT KeyState for link.
      e->Effect = DragDropEffects::Link;
   }
   else
   if ( (e->KeyState & 4) == 4 && ((e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move) )
   {
      // SHIFT KeyState for move.
      e->Effect = DragDropEffects::Move;
   }
   else
   if ( (e->KeyState & 8) == 8 && ((e->AllowedEffect & DragDropEffects::Copy) == DragDropEffects::Copy) )
   {
      // CTL KeyState for copy.
      e->Effect = DragDropEffects::Copy;
   }
   else
   if ( (e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move )
   {
      // By default, the drop action should be move, if allowed.
      e->Effect = DragDropEffects::Move;
   }
   else
	   e->Effect = DragDropEffects::None;

    // Get the index of the item the mouse is below.
   // The mouse locations are relative to the screen, so they must be
   // converted to client coordinates.
   TreeNode^node = this->m_TreeView->GetNodeAt( m_TreeView->PointToClient( Point(e->X,e->Y) ) );

   // Updates the label text.
   if ( node != nullptr )
   {
	   Mainform::Instance->SetStatusBarInfo(System::String::Concat( "Drops before item # ", (node->Text + 1) ));
   }
   else
       Mainform::Instance->SetStatusBarInfo("Drops at the end.");
}

System::Void ProjectResourcesForm::m_TreeView_GiveFeedback(System::Object^  sender, System::Windows::Forms::GiveFeedbackEventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_QueryContinueDrag(System::Object^  sender, System::Windows::Forms::QueryContinueDragEventArgs^  e)
{
}


/////////////
System::Void ProjectResourcesForm::m_TreeView_AfterLabelEdit(System::Object^  sender, System::Windows::Forms::NodeLabelEditEventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_AfterSelect(System::Object^  sender, System::Windows::Forms::TreeViewEventArgs^  e)
{
}

//////////////
System::Void ProjectResourcesForm::m_TreeView_ItemDrag(System::Object^  sender, System::Windows::Forms::ItemDragEventArgs^  e)
{
}


////////
System::Void ProjectResourcesForm::m_TreeView_NodeMouseClick(System::Object^  sender, System::Windows::Forms::TreeNodeMouseClickEventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_NodeMouseDoubleClick(System::Object^  sender, System::Windows::Forms::TreeNodeMouseClickEventArgs^  e)
{
}

/////
System::Void ProjectResourcesForm::m_TreeView_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_MouseEnter(System::Object^  sender, System::EventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_MouseLeave(System::Object^  sender, System::EventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_MouseMove(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
}

System::Void ProjectResourcesForm::m_TreeView_MouseUp(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
}

//file system watcher
System::Void ProjectResourcesForm::m_FileSystemWatcher_Changed(System::Object^  sender, System::IO::FileSystemEventArgs^  e)
{
	ConsoleForm::Instance->logMessage(e->Name + " has changed");
}

System::Void ProjectResourcesForm::m_FileSystemWatcher_Created(System::Object^  sender, System::IO::FileSystemEventArgs^  e)
{
ConsoleForm::Instance->logMessage(e->Name + " Created");
}

System::Void ProjectResourcesForm::m_FileSystemWatcher_Deleted(System::Object^  sender, System::IO::FileSystemEventArgs^  e)
{
ConsoleForm::Instance->logMessage(e->Name + " Deleted");
}

System::Void ProjectResourcesForm::m_FileSystemWatcher_Renamed(System::Object^  sender, System::IO::RenamedEventArgs^  e)
{
ConsoleForm::Instance->logMessage(e->Name + " Renamed");
}